﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

namespace UnityNetwork
{
    public class MyEventHandler
    {
        public delegate void OnReceive(Packet packet);  // 消息回调
        protected Dictionary<int, OnReceive> handlers;  // 事件消息对应表
        protected Queue<Packet> packets = new Queue<Packet>();  // 数据包队列

        public void Clear()
        {
            handlers.Clear();
            packets.Clear();
        }

        public MyEventHandler()
        {
            handlers = new Dictionary<int, OnReceive>();
        }

        public virtual void AddHandler(int msgid, OnReceive handler)
        {
            handlers.Add(msgid, handler);
        }

        public virtual void AddPacket(Packet packet)
        {
            lock (packets)
            {
                packets.Enqueue(packet);
            }
        }

        public Packet GetPacket()
        {
            lock (packets)
            {
                if (packets.Count == 0)
                    return null;
                return packets.Dequeue();
            }
        }

        public void ProcessPackets()
        {
            Packet packet = null;
            for (packet = GetPacket(); packet != null;)
            {
                OnReceive handler = null;
                if (handlers.TryGetValue(packet.msgid, out handler))
                {
                    if (handler != null)
                    {
                        handler(packet);
                    }
                }
                packet = GetPacket();
            }
        }
    }
}
